<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'bus:sh:yfShRecord:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBusShYfShRecordForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { YfShRecord, yfShRecordSave, yfShRecordForm } from '/@/api/bus/sh/yfShRecord';
  import { empUserTreeData } from '/@/api/sys/empUser';
  import { m8ViewCarTreeData } from '/@/api/bas/car/m8ViewCar';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('bus.sh.yfShRecord');
  const { showMessage } = useMessage();
  const record = ref<YfShRecord>({} as YfShRecord);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增收运记录') : t('编辑收运记录'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('医院编码'),
      field: 'hospCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
      show: false,
      required: true,
    },
    {
      label: t('医院名称'),
      field: 'hospName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
      required: true,
    },
    {
      label: t('车牌号'),
      field: 'carNo',
      component: 'TreeSelect',
      componentProps: {
        api: m8ViewCarTreeData,
        params: { isShowCode: false },
        canSelectParent: false,
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('驾驶员'),
      field: 'driverName',
      fieldLabel: 'driverName',
      component: 'TreeSelect',
      componentProps: {
        api: empUserTreeData,
        params: { officeCode: '01002' },
        canSelectParent: false,
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('押运员'),
      field: 'driver2Name',
      fieldLabel: 'driver2Name',
      component: 'TreeSelect',
      componentProps: {
        api: empUserTreeData,
        params: { officeCode: '01002' },
        canSelectParent: false,
        allowClear: true,
      },
      // required: true,
    },
    {
      label: t('感染数(箱)'),
      field: 'qtyGr',
      component: 'InputNumber',
      componentProps: ({ formModel }) => {
        return {
          onChange: (v) => {
            formModel['qtySum'] = formModel['qtyPs'] + v;
          },
        };
      },
      // rules: [
      //   { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      // ],
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('损伤数(箱)'),
      field: 'qtyPs',
      component: 'InputNumber',
      // componentProps: {
      //   maxlength: 16,
      // },
      componentProps: ({ formModel }) => {
        return {
          onChange: (v) => {
            formModel['qtySum'] = formModel['qtyGr'] + v;
          },
        };
      },
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('总数(箱)'),
      field: 'qtySum',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
        maxlength: 16,
      },
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('感染性(kg)'),
      field: 'weightGr',
      component: 'InputNumber',
      componentProps: ({ formModel }) => {
        return {
          onChange: (v) => {
            formModel['weightSum'] = (formModel['weightPs'] + v).toFixed(2);
          },
        };
      },
      rules: [{ required: true }, { pattern: /^\d+(\.\d{1,2})?$/, message: t('请保留2位小数') }],
    },
    {
      label: t('损伤性(kg)'),
      field: 'weightPs',
      component: 'InputNumber',
      componentProps: ({ formModel }) => {
        return {
          onChange: (v) => {
            formModel['weightSum'] = (formModel['weightGr'] + v).toFixed(2);
          },
        };
      },
      rules: [{ required: true }, { pattern: /^\d+(\.\d{1,2})?$/, message: t('请保留2位小数') }],
    },
    {
      label: t('总量(kg)'),
      field: 'weightSum',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
        maxlength: 16,
      },
      rules: [{ required: true }, { pattern: /^\d+(\.\d{1,2})?$/, message: t('请保留2位小数') }],
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await yfShRecordForm(data);
    record.value = (res.yfShRecord || {}) as YfShRecord;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      console.log(data, 'data=====');
      const res = await yfShRecordSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
